package com.nsgf.library.ui.page.home;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.MessageBean;
import com.nsgf.library.data.bean.ProductBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.XBannerBeanInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.glide.GlideImgManager;
import com.nsgf.library.ui.CategoryActivity;
import com.nsgf.library.ui.adapter.HomeLabelGateTitleListAdapter;
import com.nsgf.library.ui.adapter.HomeLabelListAdapter;
import com.nsgf.library.ui.mine.SignInActivity;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.LoginActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.ui.product.CouponListActivity;
import com.nsgf.library.ui.product.ExpectationListActivity;
import com.nsgf.library.ui.product.NewComersActivity;
import com.nsgf.library.ui.product.ProduceListActivity;
import com.nsgf.library.ui.product.ProductDetailActivity;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.stx.xhb.xbanner.XBanner;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.DialogHomeSalesCouponBinding;
import com.zhht.htzx.databinding.DialogHomeSalesViewBinding;
import com.zhht.htzx.databinding.DialogHomeViewBinding;
import com.zhht.htzx.databinding.FragmentNsgfHomeBinding;
import com.zhht.htzx.databinding.ItemHomeNewPeopleBinding;
import com.zhht.htzx.databinding.ItemMiniNewComersBinding;
import com.zhht.htzx.ui.BusinessNewSettledActivity;
import com.zhht.htzx.ui.BusinessSettledActivity;
import com.zhht.htzx.ui.NoticesListActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseFragment {

    private HomeFragmentStates mStates;

    private FragmentNsgfHomeBinding mBinding;
    private HomeLabelListAdapter mAdapter;
    private HomeLabelGateTitleListAdapter mAdapterGate;
    private SimpleDataBindingAdapter<ProductBean, ItemHomeNewPeopleBinding> mAdapterGateTitle;
    private List<LibraryInfo> mDatas = new ArrayList<>();
    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(HomeFragmentStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    private Dialog dialogSales;

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new HomeLabelListAdapter(getContext());

        mAdapterGateTitle = new SimpleDataBindingAdapter<ProductBean, ItemHomeNewPeopleBinding>(getActivity(), R.layout.item_home_new_people, new DiffUtil.ItemCallback<ProductBean>() {
            @Override
            public boolean areItemsTheSame(@NonNull ProductBean oldItem, @NonNull ProductBean newItem) {
                return false;
            }

            @Override
            public boolean areContentsTheSame(@NonNull ProductBean oldItem, @NonNull ProductBean newItem) {
                return false;
            }
        }) {
            @Override
            protected void onBindItem(ItemHomeNewPeopleBinding binding, ProductBean item, RecyclerView.ViewHolder holder) {

                binding.setVm(item);

            }
        };

        mAdapterGate = new HomeLabelGateTitleListAdapter(getContext());
        return new DataBindingConfig(R.layout.fragment_nsgf_home, BR.vm, mStates)
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapterGateTitle, mAdapterGateTitle)
                .addBindingParam(BR.adapterGate, mAdapterGate);
    }

    private List<XBannerBeanInfo> banners = new ArrayList<>();

    private List<Fragment> fragmentList = new ArrayList<>();

    private String[] mPageTitleList;

    @Override
    public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);


        mBinding = (FragmentNsgfHomeBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);

        mAccountRequester.getDiamonds();
        mAccountRequester.getLibraryList().observe(this, new Observer<ResponseStatus<List<LibraryInfo>>>() {
            @Override
            public void onChanged(ResponseStatus<List<LibraryInfo>> listResponseStatus) {

                if (listResponseStatus.getResponseCode() == 0) {

                    mStates.list.set(listResponseStatus.getData());
                }

            }
        });

        mAdapter.notifyDataSetChanged();
        mBinding.recyclerViewHot.setItemAnimator(null);
        mBinding.recyclerViewNew.setItemAnimator(null);

        mAdapter.setOnItemClickListener((viewId, item, position) -> {
//            if (position == 4) {
//                if (StringUtil.isEmpty(UserInfo.getInstance().getTokenValue()))
//                    startActivity(new Intent().setClass(getActivity(), LoginActivity.class));
//                else
//                    startActivity(new Intent().setClass(getActivity(), BusinessNewSettledActivity.class));
//            } else
            if (position < 4) {
                startActivity(new Intent()
                        .putExtra("title", item.getDiamondName())
                        .putExtra("position", position)
                        .setClass(getActivity(), ProduceListActivity.class));
            } else {

                startActivity(new Intent()
                        .putExtra("title", item.getDiamondName())
                        .setClass(getActivity(), ExpectationListActivity.class));

            }
        });

        mAdapterGate.setOnItemClickListener((viewId, item, position) -> startActivity(new Intent()
                .putExtra("id", item.getSpuId())
                .setClass(getActivity(), ProductDetailActivity.class)));
        mAdapterGateTitle.setOnItemClickListener((viewId, item, position) -> startActivity(new Intent()
                .putExtra("id", item.getSpuId())
                .setClass(getActivity(), ProductDetailActivity.class)));


        mBinding.marqueeText.setSelected(true);  // 必须设置


        mBinding.etHomeSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 在这里执行搜索操作
                    startActivity(new Intent()
                            .putExtra("searchName", mBinding.etHomeSearch.getText().toString())
                            .putExtra("position", -1)
                            .setClass(getActivity(), ProduceListActivity.class));
                    return true; // 消费事件，防止默认行为
                }
                return false; // 不消费事件，允许默认行为
            }
        });


        mAccountRequester.getProductResult().observe(this, new Observer<ResponseStatus<ProductBean>>() {
            @Override
            public void onChanged(ResponseStatus<ProductBean> productBeanResponseStatus) {

                if (productBeanResponseStatus.getResponseCode() == 0) {

                    if (null == dialogSales)
                        dialogSales = new Dialog(getActivity());
                    else {
                        if (dialogSales.isShowing())
                            dialogSales.dismiss();
                    }
                    View view = View.inflate(getActivity(), R.layout.dialog_home_sales_view, null);
                    DialogHomeSalesViewBinding viewBinding = DataBindingUtil.bind(view);
                    viewBinding.recyclerView.setItemAnimator(null);
                    HomeFragmentStates dialogStates = new HomeFragmentStates();
                    List<ProductBean> list = new ArrayList<>();
                    for (int i = 0; i < 2; i++) {
                        list.add(productBeanResponseStatus.getData().getList().get(i));
                    }
                    dialogStates.dialogGoods.set(list);
                    viewBinding.setVm(dialogStates);
                    viewBinding.ivDialogClose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialogSales.dismiss();
                        }
                    });
                    viewBinding.getRoot().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            startActivity(new Intent().setClass(getActivity(), NewComersActivity.class));
                            dialogSales.dismiss();
                        }
                    });
                    viewBinding.setAdapter(new SimpleDataBindingAdapter<ProductBean,
                            ItemMiniNewComersBinding>(getActivity(), R.layout.item_mini_new_comers,
                            new DiffUtil.ItemCallback() {
                                @Override
                                public boolean areItemsTheSame(@NonNull Object oldItem, @NonNull Object newItem) {
                                    return false;
                                }

                                @Override
                                public boolean areContentsTheSame(@NonNull Object oldItem, @NonNull Object newItem) {
                                    return false;
                                }
                            }) {
                        @Override
                        protected void onBindItem(ItemMiniNewComersBinding binding, ProductBean item, RecyclerView.ViewHolder holder) {
                            binding.setVm(item);
                            setOnItemClickListener(new OnItemClickListener<ProductBean>() {
                                @Override
                                public void onItemClick(int viewId, ProductBean item, int position) {
                                    startActivity(new Intent()
                                            .putExtra("id", item.getSpuId())
                                            .setClass(getActivity(), ProductDetailActivity.class));
                                    dialogSales.dismiss();
                                }
                            });
                        }
                    });
                    dialogSales.setContentView(view);

                    Window window = dialogSales.getWindow();
                    window.setBackgroundDrawableResource(android.R.color.transparent);
                    WindowManager.LayoutParams lp = window.getAttributes();
                    window.setAttributes(lp);
                    window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
                    dialogSales.show();
                }
            }
        });

        //热销商品底部商品列表
        mAccountRequester.getSpuList();
        //banner广告位
        mAccountRequester.getLunBoList();
        //公告通知
        mAccountRequester.getNotices();
        //弹窗展示逻辑
        shopDialog();
        mAccountRequester.getMessageListResult().observe(this, new Observer<ResponseStatus<List<MessageBean.DataBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<MessageBean.DataBean>> listResponseStatus) {
                if (listResponseStatus.getResponseCode() == 0) {
                    if (!listResponseStatus.getData().isEmpty()) {
                        if (listResponseStatus.getData().size() > 0) {

                            StringBuilder text = new StringBuilder(listResponseStatus.getData().get(0).getTitle());
                            int minLength = 80; //
                            while (text.length() < minLength) {
                                text.append("   "); // text += " "; 只加空格
                            }
                            mBinding.marqueeText.setText(text.toString());
                            mBinding.marqueeText.setEllipsize(TextUtils.TruncateAt.MARQUEE);
                            mBinding.marqueeText.setMarqueeRepeatLimit(-1);  // 无限循环
                            mBinding.marqueeText.setSingleLine(true);
                        }
                    }
                }
            }
        });
        mAccountRequester.getBannerResult().observe(this, new Observer<ResponseStatus<List<ProductBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<ProductBean>> listResponseStatus) {

                if (listResponseStatus.getResponseCode() == 0) {

                    for (ProductBean bean : listResponseStatus.getData()) {

                        XBannerBeanInfo info = new XBannerBeanInfo(bean.getPicUrl(), bean.getSpuId());
                        banners.add(info);
                    }

                    mBinding.xbanner.setBannerData(banners);
                    mBinding.xbanner.loadImage((banner, model, view, position) -> {
                        String url = (String) ((XBannerBeanInfo) model).getXBannerUrl();
                        GlideImgManager.getInstance().glideLoaderBannerCenterCrop(getActivity(),
                                url.replace("\\", "/"), (ImageView) view, 10);
                    });
                    mBinding.xbanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                        @Override
                        public void onItemClick(XBanner banner, Object model, View view, int position) {

                            startActivity(new Intent()
                                    .putExtra("id", ((XBannerBeanInfo) model).getId())
                                    .setClass(getActivity(), ProductDetailActivity.class));
                        }
                    });

                }
            }
        });

        mAccountRequester.getProductBeanResult().observe(this, new Observer<ResponseStatus<List<ProductBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<ProductBean>> listResponseStatus) {

                if (listResponseStatus.getResponseCode() == 0) {
                    mStates.listGate.set(listResponseStatus.getData());
                    mAdapterGate.notifyDataSetChanged();
                }
            }
        });

        mAccountRequester.getQueryDiscountedProductsResult().observe(this, new Observer<ResponseStatus<ProductBean>>() {
            @Override
            public void onChanged(ResponseStatus<ProductBean> listResponseStatus) {
                if (listResponseStatus.getResponseCode() == 0) {
                    mStates.listGateTitle.set(listResponseStatus.getData().getList());
                    mAdapterGateTitle.notifyDataSetChanged();
                    if ("2".equals(UserInfo.getInstance().getReceiveStatus())) {

                        if (null == dialogSales)
                            dialogSales = new Dialog(getActivity());
                        else {
                            if (dialogSales.isShowing())
                                dialogSales.dismiss();
                        }
                        View view = View.inflate(getActivity(), R.layout.dialog_home_view, null);
                        DialogHomeViewBinding viewBinding = DataBindingUtil.bind(view);
                        viewBinding.recyclerView.setItemAnimator(null);
                        HomeFragmentStates dialogStates = new HomeFragmentStates();
                        List<ProductBean> list = new ArrayList<>();
                        if (mStates.listGateTitle.get().size()>1){
                        for (int i = 0; i < 2; i++) {
                            list.add(mStates.listGateTitle.get().get(i));
                        }
                        }
                        dialogStates.dialogGoods.set(list);
                        viewBinding.setVm(dialogStates);
                        viewBinding.ivDialogClose.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialogSales.dismiss();
                            }
                        });
                        viewBinding.llDialogHomeBg.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                startActivity(new Intent().setClass(getActivity(), NewComersActivity.class));
                                dialogSales.dismiss();
                            }
                        });
                        viewBinding.setAdapter(new SimpleDataBindingAdapter<ProductBean,
                                ItemMiniNewComersBinding>(getActivity(), R.layout.item_mini_new_comers,
                                new DiffUtil.ItemCallback() {
                                    @Override
                                    public boolean areItemsTheSame(@NonNull Object oldItem, @NonNull Object newItem) {
                                        return false;
                                    }

                                    @Override
                                    public boolean areContentsTheSame(@NonNull Object oldItem, @NonNull Object newItem) {
                                        return false;
                                    }
                                }) {
                            @Override
                            protected void onBindItem(ItemMiniNewComersBinding binding, ProductBean item, RecyclerView.ViewHolder holder) {
                                binding.setVm(item);
                                binding.tvItemMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                                setOnItemClickListener(new OnItemClickListener<ProductBean>() {
                                    @Override
                                    public void onItemClick(int viewId, ProductBean item, int position) {
                                        startActivity(new Intent()
                                                .putExtra("id", item.getSpuId())
                                                .setClass(getActivity(), ProductDetailActivity.class));
                                        dialogSales.dismiss();
                                    }
                                });
                            }
                        });
                        dialogSales.setContentView(view);

                        Window window = dialogSales.getWindow();
                        window.setBackgroundDrawableResource(android.R.color.transparent);
                        WindowManager.LayoutParams lp = window.getAttributes();
//                        lp.width = getResources().getDisplayMetrics().widthPixels;
                        window.setAttributes(lp);
                        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
                        dialogSales.show();
                    }

                }
            }
        });

        EventBus.getDefault().register(this);
    }

    /**
     *
     */
    private void shopDialog() {

        if (isHidden())
            return;

        //新人专享
        mAccountRequester.queryDiscountedProducts(3);
        if ("2".equals(UserInfo.getInstance().getReceiveStatus())) {
        } else if ("3".equals(UserInfo.getInstance().getReceiveStatus())) {//领券已消费
            mAccountRequester.queryHotSales();//弹窗热门商品
        } else {//未领或新用户

            if (null == dialogSales)
                dialogSales = new Dialog(getActivity());
            else {
                if (dialogSales.isShowing())
                    dialogSales.dismiss();
            }
            View view = View.inflate(getActivity(), R.layout.dialog_home_sales_coupon, null);
            DialogHomeSalesCouponBinding viewBinding = DataBindingUtil.bind(view);
            viewBinding.ivDialogClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialogSales.dismiss();
                }
            });
            viewBinding.getRoot().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
                        startActivity(new Intent().setClass(getActivity(), CouponListActivity.class));
                    } else {
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }
                    dialogSales.dismiss();
                }
            });
            dialogSales.setContentView(view);

            Window window = dialogSales.getWindow();
            window.setBackgroundDrawableResource(android.R.color.transparent);
            WindowManager.LayoutParams lp = window.getAttributes();
//            lp.width = getResources().getDisplayMetrics().widthPixels;
            window.setAttributes(lp);
            window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
            dialogSales.show();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.e("hidden", "hidden：" + hidden);
        if (!hidden)
            shopDialog();
        else {
            if (null != dialogSales) {
                if (dialogSales.isShowing())
                    dialogSales.dismiss();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    //登录后通知
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMsg event) {
        if ("dialog".equals(event.getMsg())) {
            shopDialog();
        }
    }

    public static class HomeFragmentStates extends StateHolder {

        public final State<String> name = new State<>(UserInfo.getInstance().getName());

        public final State<List<LibraryInfo>> list = new State<>(new ArrayList<>());
        public final State<List<ProductBean>> listGate = new State<>(new ArrayList<>());
        public final State<List<ProductBean>> listGateTitle = new State<>(new ArrayList<>());
        public final State<List<ProductBean>> dialogGoods = new State<>(new ArrayList<>());
        public final State<Boolean> loadingVisible = new State<>(false);


    }

    public class ClickProxy {

        public void gotoCategory() {
            startActivity(new Intent().setClass(getActivity(), CategoryActivity.class));
        }

        public void gotoNotices() {
            startActivity(new Intent().setClass(getActivity(), NoticesListActivity.class));
        }

        public void gotoCoupon() {
            if (!StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
                startActivity(new Intent().setClass(getActivity(), CouponListActivity.class));
            } else {
                startActivity(new Intent(getActivity(), LoginActivity.class));
            }
        }

        public void gotoSignIn() {
            if (!StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
                startActivity(new Intent(getActivity(), SignInActivity.class));
            } else {
                startActivity(new Intent(getActivity(), LoginActivity.class));
            }
        }
    }


}
